//
//  BankCardAddController.swift
//  mggz
//
//  Created by ShareAnimation on 2017/8/28.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit

class BankCardAddController: UIViewController, UITextFieldDelegate {
    
    
    /// 用户名
    fileprivate var usernameTextField: UITextField = {
        let textField = UITextField()
       // textField.placeholder = "请输入持卡人姓名(需与认证姓名一致)"
        textField.backgroundColor = UIColor.white
        textField.isEnabled = false
        let leftView = UIView()
        leftView.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
        let imageView = UIImageView()
        imageView.image = UIImage(named: "Icon_用户名")!.withRenderingMode(.alwaysTemplate)
        imageView.tintColor = UIColor.mg_lightGray
        imageView.contentMode = .scaleAspectFit
        leftView.addSubview(imageView)
        imageView.snp.makeConstraints({ (make) in
            make.center.equalTo(leftView)
            make.left.equalTo(leftView).offset(10)
            make.right.equalTo(leftView).offset(-10)
            make.width.equalTo(imageView.snp.height)
        })
        textField.leftView = leftView
        textField.leftViewMode = .always
        
        return textField
    }()
    
    /// 开户银行
    fileprivate var depositBankTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "请选中持卡开户银行"
        textField.backgroundColor = UIColor.white
        //        textField.isUserInteractionEnabled = true
        
        let leftView = UIView()
        leftView.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
        let imageView = UIImageView()
        imageView.image = UIImage(named: "Icon_银行开户")!.withRenderingMode(.alwaysTemplate)
        imageView.tintColor = UIColor.mg_lightGray
        imageView.contentMode = .scaleAspectFit
        leftView.addSubview(imageView)
        imageView.snp.makeConstraints({ (make) in
            make.center.equalTo(leftView)
            make.left.equalTo(leftView).offset(10)
            make.right.equalTo(leftView).offset(-10)
            make.width.equalTo(imageView.snp.height)
        })
        textField.leftView = leftView
        textField.leftViewMode = .always
        
        return textField
    }()
    
    fileprivate var rightView: UIView = {
        let rightView = UIView()
        rightView.backgroundColor = UIColor.white
        rightView.isUserInteractionEnabled = true
        
        let rightImageView = UIImageView()
        rightImageView.image = UIImage(named: "Icon_右箭头")!.withRenderingMode(.alwaysTemplate)
        rightImageView.tintColor = UIColor.mg_lightGray
        rightImageView.contentMode = .scaleAspectFit
        rightView.addSubview(rightImageView)
        rightImageView.snp.makeConstraints({ (make) in
            make.center.equalTo(rightView)
            make.left.equalTo(rightView).offset(10)
            make.right.equalTo(rightView).offset(-10)
            make.width.equalTo(rightImageView.snp.height)
        })
        
        return rightView
    }()
    
    /// 卡号
    fileprivate var cardNoTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "请输入持卡开户银行卡号"
        textField.backgroundColor = UIColor.white
        textField.keyboardType = .decimalPad
        
        let leftView = UIView()
        leftView.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
        let imageView = UIImageView()
        imageView.image = UIImage(named: "Icon_银行卡")!.withRenderingMode(.alwaysTemplate)
        imageView.tintColor = UIColor.mg_lightGray
        imageView.contentMode = .scaleAspectFit
        leftView.addSubview(imageView)
        imageView.snp.makeConstraints({ (make) in
            make.center.equalTo(leftView)
            make.left.equalTo(leftView).offset(10)
            make.right.equalTo(leftView).offset(-10)
            make.width.equalTo(imageView.snp.height)
        })
        textField.leftView = leftView
        textField.leftViewMode = .always
        
        return textField
    }()
    
    fileprivate lazy var addButton: UIButton = {
        let button = UIButton()
        button.backgroundColor = UIColor.mg_blue
        if self.entranceOption == .bankChoice {
            button.setTitle("确认绑卡", for: .normal)
        }
        else {
            button.setTitle("提交认证", for: .normal)
        }
        
        button.titleLabel?.font = wwFont_Medium(17)
        button.layer.shadowColor = UIColor.black.cgColor
        button.layer.shadowOffset = CGSize(width: 1, height: 1)
        button.layer.shadowOpacity = 0.3
        button.layer.cornerRadius = 6
        return button
    }()
    fileprivate lazy var messageImage:UIImageView = {
        let messageImage = UIImageView.init()
        messageImage.image = UIImage(named: "retn_bankcon")
        return messageImage
    }()
    fileprivate lazy var messageLabel:UILabel = {
       let label = UILabel.init()
        label.text = "为确保工资提现成功，请确保绑定本人的银行卡！"
        label.font = wwFont_Regular(12)
        label.numberOfLines = 0
        label.textColor = UIColor(red: 0.96, green: 0.65, blue: 0.14, alpha: 1)
        return label
    }()
    
    private var currentBankModel: BankModel?//当前选中的银行
    var addFinishHandler:(() -> Void)?
    
    var userInfoModel: UserInfoModel?//用户信息
    
    //判断是哪个页面进入的
    enum BankCardAddControllerOption {
        case certification //如果是提交认证时进来
        case bankChoice //选择银行卡界面进来
    }
    
    //默认选择银行卡界面进入
    var entranceOption = BankCardAddControllerOption.bankChoice
    
    init(_ option: BankCardAddControllerOption) {
        super.init(nibName: nil, bundle: nil)
        self.entranceOption = option
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        WWProgressHUD.dismiss()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        if self.entranceOption == .bankChoice {
            self.title = "添加银行卡"
        }
        else {
            self.title = "绑定提现银行卡"
            self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "跳过", style: .done, target: self, action: #selector(doSkipStepAction))
        self.navigationItem.rightBarButtonItem?.setTitleTextAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 15)], for: .normal)
        }
        
        self.view.backgroundColor = UIColor.mg_backgroundGray
        
        self.addButton.addTarget(self, action: #selector(doAddAction), for: .touchUpInside)
        self.depositBankTextField.delegate = self
        
        self.setupViews()
        
        self.getUserInformation()
    }
    
    private func getUserInformation() {
        UserInfoModel.getMigrantWorkInfo { (response) in
            if response.success {
                self.userInfoModel = response.value
                self.usernameTextField.text = self.userInfoModel?.username
            }
            else {
                WWError(response.message)
            }
        }
    }
    
    func setupViews() {
        self.view.addSubview(self.usernameTextField)
        self.usernameTextField.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.view).offset(64)
            make.height.equalTo(50)
        }
        
        self.view.addSubview(self.depositBankTextField)
        self.depositBankTextField.snp.makeConstraints { (make) in
            make.left.equalTo(self.view)
            make.top.equalTo(self.usernameTextField.snp.bottom)
            make.height.equalTo(self.usernameTextField)
        }
        
        self.rightView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(doRightTapAction)))
        self.view.addSubview(self.rightView)
        self.rightView.snp.makeConstraints { (make) in
            make.left.equalTo(self.depositBankTextField.snp.right)
            make.right.equalTo(self.view)
            make.height.equalTo(self.rightView.snp.width)
            make.top.bottom.equalTo(self.depositBankTextField)
        }
        
        
        self.view.addSubview(self.cardNoTextField)
        self.cardNoTextField.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.depositBankTextField.snp.bottom)
            make.height.equalTo(self.usernameTextField)
        }
        
        self.view.addSubview(self.addButton)
        self.addButton.snp.makeConstraints { (make) in
        make.top.equalTo(self.cardNoTextField.snp.bottom).offset(80)
            make.left.equalTo(self.view).offset(30)
            make.right.equalTo(self.view).offset(-30)
            make.height.equalTo(45)
            
        }
        self.view.addSubview(self.messageImage)
        self.messageImage.snp.makeConstraints { (make) in
            make.top.equalTo(self.addButton.snp.bottom).offset(10.5)
                make.leading.equalTo(self.addButton)
                make.size.equalTo(CGSize(width: 12, height: 12))
        }
        self.view.addSubview(self.messageLabel)
        self.messageLabel.snp.makeConstraints { (make) in
            make.left.equalTo(self.messageImage.snp.right).offset(5)
                make.trailing.equalTo(self.addButton)
               // make.height.equalTo(16)
            make.top.equalTo(self.addButton.snp.bottom).offset(8)
        }
    }
    
    func doRightTapAction() {
        let vc = BankChoiceController()
        vc.selectHandler = {[unowned self](response) in
            self.depositBankTextField.text = response.bankName
            self.currentBankModel = response
        }
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func doSkipStepAction() {
        
    }
    
    func doAddAction() {
        guard let username = self.usernameTextField.text, username.characters.count > 0 else {
            WWError("用户名为空")
            return
        }
        guard username == self.userInfoModel?.username else{
            WWError("持卡人名字与提交的认证信息不同")
            return
        }
        
        guard let currentBank = self.currentBankModel, currentBank.bankId != nil else {
            WWError("开卡银行选择错误")
            return
        }
        guard let cardNo = self.cardNoTextField.text,cardNo.count > 15,cardNo.count < 20  else{
            WWError("银行卡错误,应该提供16-19数字号码")
            return
        }
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
    LCAPiSubManager.request(.AddSalaryCard(SalaryCardBankAccount: cardNo, CardholderName: username, BankInfoID: currentBank.bankId!, AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                
                guard (jsonString["Status"]) as! String == "OK" else{
                    WWError(jsonString["Result"] as! String)
                    return
                }
            self.navigationController?.popViewController(animated: true)
                WWSuccess("预支成功")
            }
        }
        
        
        
        
        
        
       
        
    }
    
    //MARK:UITextFieldDelegate
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        if textField == self.depositBankTextField {
            self.doRightTapAction()
            return false
        }
        return true
    }
}

